define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"UtilDir/loading",
	"static/app/fxpg/util/js/bootstrap-select",
	"static/app/fxpg/util/js/defaults-zh_CN",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(Util, Tool, SelectOrg, SearchBlock, Loading){

	var getFxSurveySpotQueryController = function(){
		return getServer() + "/fxSurveySpots";
	};

	var getFxCityCountyController = function () {
		return getServer() + "/fxCityCountys";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		initcreateProvince();
		initWorkspaceConditionSelect();
		initMap();
	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
			querySurveySpot();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("北京市");
			$('#workspace').selectpicker('val',"");//回到初始状态
        });
		$("#btnExport").click(function () {
			alert("功能暂未实现");
		});
		$("#fx-SurveySpot-Map-Grid-Close").click(function () {
			$("#fx-SurveySpot-attributes").hide();
		});
	};
	var initcreateProvince = function () {
		var html = "";
		$("#provinceSelect").html(html);
		$.ajax({
			url: getServer() + "/divisions/root/subdivisions",
			contentType: "application/json",
			type: "get",
			success: function (data) {
				$.each(data, function (idx, item) {
					html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
				});
				$("#provinceSelect").append(html);
			}
		});
	}
	var initWorkspaceConditionSelect = function () {
		$.ajax({
			url: getServer() + "/fxWorkareas/" + "getWorkspaces",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("workspace");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i];
					var code = data[i];
					mySelect.add(new Option(name, code));
				}
				$('.selectpicker').selectpicker({'selectedText': 'cat'});
			}
		});
	};

	var loading = Loading({text : "正在查询数据..."});
	var tdMap;
	var initMap = function () {
		var mapH = document.body.clientHeight - $(".pd-search-container").height() - 20;
		$("#fx-SurveySpot-mapDiv").height(mapH);

		var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
		var config = {
			projection: 'EPSG:4326',
			minZoom: 4,
			layers: [vec_layer, cva_layer]
		};
		tdMap = new T.Map('fx-SurveySpot-mapDiv', config), zoom = 4;
		tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);
		console.log("调查点查询！");
	};
	var querySurveySpot = function (){
		tdMap.clearOverLays();
		var province = $("#provinceSelect").val(), workspace = $("#workspace").val();
		console.log(province, workspace);
		loading.show();
		$.ajax({
			url: getFxCityCountyController() + "/getFxCityCountys?province=" + province + "&workspace=" + workspace,
			type: "GET",
			dataType: "json",
			success: function(data) {
				loading.close();
				console.log(data);
				if (data && data.length) {
					var points = [], cityCountyName = "";
					for (let idx = 0;idx < data.length;idx++) {
						cityCountyName = data[idx].cityCountyName;
						$.ajax({
							url: getFxSurveySpotQueryController() + "/getFxSurveySpots?cityCountyName=" + cityCountyName,
							type: "GET",
							dataType: "json",
							success: function(result) {
								console.log("result: ", result);
								if (result && result.length) {
									for (var k = 0;k < result.length;k++) {
										var icon = new T.Icon({
											iconUrl: "/fxpg/static/app/fxpg/fx_plugins/images/marker-red.png",
											iconSize: new T.Point(20, 20),
											iconAnchor: new T.Point(-10, -10)
										});
										var point = new T.LngLat(result[k].longitude, result[k].latitude);
										var marker = new T.Marker(point, {icon: icon, _data: result[k]});
										marker.addEventListener("click", buildingMarkerClick);
										tdMap.addOverLay(marker);
										points.push(point);
									}
									tdMap.setViewport(points);
								}
							}
						});
					}
				} else {
					Util.alert("查询无数据!");
				}
			}
		});
	};
	var buildingMarkerClick = function (e) {
		//alert(e.lnglat.getLng() + "," + e.lnglat.getLat());
		//console.log(e);
		console.log(this.options._data);
		var _data = this.options._data;
		$("#fx-SurveySpot-attributes").css("display", "block");
		var divStr = "<table class='table table-bordered table-hover table-building'>" +
			"<tbody>" +
			"<tr>" +
			"<td>省</td>" +
			"<td>" + _data.province + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>市县名称</td>" +
			"<td>" + _data.cityCountyName + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>实地调查点名称</td>" +
			"<td>" + _data.surveySpotName + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>经度</td>" +
			"<td>" + _data.longitude + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>纬度</td>" +
			"<td>" + _data.latitude + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>所属乡镇（村）</td>" +
			"<td>" + (_data.township ? _data.township : "") + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>总户数</td>" +
			"<td>" + _data.totalHouseholds + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>总人口</td>" +
			"<td>" + _data.totalPopulation + "</td>" +
			"</tr>" +
			"<tr>" +
			"<td>实际常驻人口</td>" +
			"<td>" + _data.residentPopulation + "</td>" +
			"</tr>" +
			"</tbody>" +
			"</table>";
		$("#fx-SurveySpot-attributes").children().eq(1).html(divStr);
	};

	return {
		init:init
	};
});
